using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.UI;

public class Character : MonoBehaviour
{
    public Text nameText;
    public Text levelText;
    public Image headImg;
    public Text talentDescText;
    public GameObject cContainer;
    public GameObject bContainer;
    public GameObject cItemPrefab;

    public int currentIndex = 0;
    private const string KEY = "PersonLevel_";

    public Text upgradeText;

    public static Character Instance;
    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
        }

        if (!PlayerPrefs.HasKey("CharacterCurrentIndex"))
        {
            PlayerPrefs.SetInt("CharacterCurrentIndex", 0);
            PlayerPrefs.Save();

        }
        GlobalEventManager.OnEvent<int>("UpdateHeadInfo", OnUpdateHeadInfo);

        if (!PlayerPrefs.HasKey("PersonLevel_0"))
        {
            // 初始化人物等级
            for (int i = 0; i < 4; i++)
            {
                PlayerPrefs.SetInt(KEY + i, 1);
                PlayerPrefs.Save();
            }
        }
    }

    void Start()
    {


    }

    //获取人物等级
    public int GetPersonLevel(int index)
    {
        return PlayerPrefs.GetInt(KEY + index, 1);
    }

    //升级人物等级
    public void UpgradePersonLevel(int index)
    {
        int level = GetPersonLevel(index);
        if (level >= 8)
        {
            Tools.ShowTipToast("You have reached the maximum level.");
            return;
        }

        level++;
        PlayerPrefs.SetInt(KEY + index, level);
        PlayerPrefs.Save();
    }

    public void ShowCharacterList()
    {
        currentIndex = PlayerPrefs.GetInt("CharacterCurrentIndex");

        RenderCList();
        RenderBList();
    }

    private void OnUpdateHeadInfo(int index)
    {
        JObject data = Data.touxiangpeizhi[index].ToObject<JObject>();
        int lv = GetPersonLevel(index);

        if (data == null) return;
        nameText.text = data["name"].ToString();
        headImg.sprite = ResManager.Instance.GetHeadIcons()[index];
        string desc = data["talent"].ToString();
        string newDesc = desc.Replace("{{talent_value}}", data["talent_value"][lv - 1].ToString());
        talentDescText.text = newDesc;


        levelText.text = $"lv.{lv}";

        foreach (Transform item in cContainer.transform)
        {
            LittleHead littleHead = item.GetComponent<LittleHead>();
            if (littleHead != null)
            {
                littleHead.selectedImg.SetActive(false);
            }
        }

        upgradeText.text = Data.touxiangpeizhi[index]["talent_cost"][lv - 1].ToString();
    }

    private void RenderCList()
    {
        foreach (Transform item in cContainer.transform)
        {
            Destroy(item.gameObject);
        }

        for (int i = 0; i < 4; i++)
        {
            GameObject prefab = Instantiate(cItemPrefab, cContainer.transform);
            prefab.GetComponent<LittleHead>().InitHead(i);
        }
    }

    private void RenderBList()
    {
        foreach (Transform item in bContainer.transform)
        {
            Destroy(item.gameObject);
        }

        for (int i = 4; i < 8; i++)
        {
            GameObject prefab = Instantiate(cItemPrefab, bContainer.transform);
            prefab.GetComponent<LittleHead>().InitHead(i);
        }
    }

    public void OnUpgradeClick()
    {
        float coins = UserManager.Instance.GetUserInfo()["Coins"].ToObject<float>();
        float cost;
        if (float.TryParse(upgradeText.text, out cost))
        {
            // 成功转换，继续处理逻辑
            if (coins < cost)
            {
                Tools.ShowTipToast("You don't have enough coins to upgrade.");
                return;
            }
            UpgradePersonLevel(currentIndex);
            OnUpdateHeadInfo(currentIndex);
            GlobalEventManager.EmitEvent<int>("UpdateLevelInfo", currentIndex);
            UserManager.Instance.SubtractCoins(cost);
            Tools.ShowTipToast("Great!");
        }
    }

    public void OnSelectClick()
    {
        PlayerPrefs.SetInt("CharacterCurrentIndex", currentIndex);
        PlayerPrefs.Save();
        Tools.ShowTipToast("Selected!");
    }
}
